package com.zxing;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.Region;
import android.text.TextUtils;

import java.io.File;
import java.io.FileOutputStream;

/**
 * 截图 Created by res-zwyan on 2015/6/19.
 */
public class ScreenshotUtils
{
    /**
     * 根据提供的至少三个点截图
     * 
     * @param bitmap
     *            源图
     * @param points
     *            至少三个点
     * @param savePath
     *            保存图片路径
     * @param fileName
     *            保存图片的文件名称(不包含路径)
     * @return 保存文件的名称+路径 如果返回的null说明截图失败
     */
    public static String parse(Bitmap bitmap, Point[] points, String savePath,
            String fileName)
    {
        String path = null;
        if (bitmap == null || bitmap.isRecycled() || points == null
                || points.length < 2 || TextUtils.isEmpty(savePath))
        {
            return path;
        }
        Bitmap temBitmap = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        File saveFile = new File(savePath);
        if (!saveFile.exists())
        {
            saveFile.mkdirs();
        }
        Canvas canvas = new Canvas(temBitmap);
        int pointLen = points.length;
        Path drawPath = new Path();
        drawPath.moveTo(points[0].x, points[0].y);
        for (int i = 1; i < pointLen; i++)
        {
            drawPath.lineTo(points[i].x, points[i].y);
        }
        drawPath.close();
        canvas.clipPath(drawPath, Region.Op.INTERSECT);
        canvas.drawBitmap(bitmap, 0, 0, null);
        try
        {
            File tempFile = new File(saveFile, fileName);
            if (!tempFile.exists())
            {
                tempFile.createNewFile();
            }
            else
            {
                tempFile.deleteOnExit();
            }
            FileOutputStream OutputStream = new FileOutputStream(tempFile);
            if (temBitmap
                    .compress(Bitmap.CompressFormat.PNG, 100, OutputStream))
            {
                return tempFile.getAbsolutePath();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (bitmap != null && !bitmap.isRecycled())
            {
                bitmap.recycle();
                bitmap = null;
            }
            if (temBitmap != null && !temBitmap.isRecycled())
            {
                temBitmap.recycle();
                temBitmap = null;
            }
        }
        return path;
    }

}
